import 'dart:convert';
import 'dart:typed_data';
import 'package:chathouse/public/Config.dart';
import 'package:chathouse/util/base_utils.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:image_picker/image_picker.dart';
import '../../constant/my_color.dart';
import 'package:flutter_image_compress/flutter_image_compress.dart';

//問題類型11 圖片選擇11 6張
//問題類型14 (14 3张可选)
class ImagePickerWidget11And14 extends StatefulWidget {
  String? title;
  String subTitle;
  List<String> imageUrls;
  Function(List<String> imageUrls) onSelectImage;
  int maxLength = 6;
  bool request;
  ImagePickerWidget11And14(this.title, this.imageUrls, this.onSelectImage,
      {this.subTitle = "最多6張圖片", int type = 11, this.request = false, Key? key})
      : super(key: key) {
    if (type == 14) {
      subTitle = "最多3張圖片";
      maxLength = 3;
    }
  }

  @override
  State<ImagePickerWidget11And14> createState() =>
      _ImagePickerWidget11And14State();
}

class _ImagePickerWidget11And14State extends State<ImagePickerWidget11And14> {
  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        padding: EdgeInsets.only(left: 26.w, right: 26.w),
        child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
          Row(crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              widget.request
                  ? Text(
                      "*",
                      style: getTextStyle(18.sp, color: Colors.red),
                    )
                  : Container(),
              Expanded(
                  child: Text(
                widget.title ?? "",
                style: getTextStyle(18.sp, color: Colors.black),
              ))
            ],
          ),
          Text(
            widget.subTitle ?? "",
            style: getTextStyle(14.sp, color: MyColors.gary_149149149),
          ).setContainer(margin: EdgeInsets.only(top: 2.w)),
          SizedBox(
            height: 12.w,
          ),
          //
          Wrap(
            spacing: 16.w,
            runSpacing: 16.w,
            children: getSubWidgets(),
          )
        ]));
  }

  List<Widget> getSubWidgets() {
    List<Widget> subWidgets = [];
    for (var element in widget.imageUrls) {
      subWidgets.add(getImageWidget(element));
    }
    if (widget.imageUrls.length < widget.maxLength) {
      subWidgets.add(getAddWidget());
    }

    return subWidgets;
  }

  Widget getImageWidget(String url) {
    double itemW = (1.sw - 26.w * 2 - 16.w * 2) / 3.0 - 0.1;
    return ClipRRect(
      child: Container(
        width: itemW,
        height: itemW,
        decoration: BoxDecoration(
            color: MyColors.gary_230230230,
            borderRadius: BorderRadius.circular(20.w)),
        child: ImageUtils.image(url,
            imageType: ImageType.NETWORK,
            width: itemW,
            height: itemW,
            key: UniqueKey()),
      ),
      borderRadius: BorderRadius.circular(20.w),
    );
  }

  Widget getAddWidget() {
    double itemW = (1.sw - 26.w * 2 - 16.w * 2) / 3.0 - 0.1;
    return Container(
      width: itemW,
      height: itemW,
      decoration: BoxDecoration(
          color: MyColors.gary_230230230,
          borderRadius: BorderRadius.circular(20.w)),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          ImageUtils.image(Res.image_pick_add, width: 51.w, height: 51.w),
          SizedBox(height: 6.w),
          Text(
            "選擇照片",
            style: getTextStyle(16.sp, color: MyColors.brow_25511377),
          ),
        ],
      ),
    ).setOnClickListener(() {
      onAddImage();
    });
  }

  void onAddImage() async {
    int type = await Get.bottomSheet(Container(
      width: 1.sw,
      height: 120.w,
      decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
              topLeft: Radius.circular(8.w), topRight: Radius.circular(8.w))),
      child: Column(
        children: [
          Text(
            "從相冊中選取",
            style: getTextStyle(18.sp, color: Colors.black),
          )
              .setContainer(
                  width: double.infinity,
                  height: 60.w,
                  alignment: Alignment.center,
                  decoration: BoxDecoration(
                      border: Border(
                          bottom: BorderSide(
                              width: 1.0.w, color: MyColors.gary_149149149))))
              .setOnClickListener(() {
            Get.back(result: 1);
          }),
          Text(
            "相機",
            style: getTextStyle(18.sp, color: Colors.black),
          )
              .setContainer(
            alignment: Alignment.center,
            width: double.infinity,
            height: 60.w,
          )
              .setOnClickListener(() {
            Get.back(result: 2);
          }),
        ],
      ),
    ));
    final ImagePicker picker = ImagePicker();
    final XFile? image = await picker.pickImage(
        source: type == 1 ? ImageSource.gallery : ImageSource.camera);
    var imgData = await image?.readAsBytes();
    if (imgData == null) return;
    Obj.showLoading();
    imgData = await testComporessList(imgData);
    Map result;
    String? url;
    Apis.uploadFile(imgData!, image?.name ?? "image.png")
        .then((response) => {
              Obj.dismissLoading(),
              debugPrint("upload=${response?.data.toString()}"),
              result = jsonDecode(response?.data ?? ""),
              url = result["url"],
              if (url != null)
                {
                  setState(() {
                    widget.imageUrls.add(url!);
                  }),
                  widget.onSelectImage(widget.imageUrls),
                }
            })
        .catchError((error) => {Obj.dismissLoading(), setState(() {})});
  }

  // 4. compress Uint8List and get another Uint8List.
  Future<Uint8List> testComporessList(Uint8List list) async {
    var result = await FlutterImageCompress.compressWithList(
      list,
      minWidth: 960,
      minHeight: 540,
      quality: 95,
      // rotate: 135,
    );
    debugPrint("testComporessList list.length=${list.length}");
    debugPrint("testComporessList result.length=${result.length}");
    return result;
  }
}
